from django.shortcuts import render
from django.http import HttpResponse
from .booktxt import *
import json

# Create your views here.


def api_search(request):
    if request.method == 'POST':
        search_info = request.POST
        keyword = search_info['keyword']
        info = Booktxt(keyword = keyword)
        info = info.novel_info()
        return HttpResponse(json.dumps(info))
    if request.method != 'POST':
        return HttpResponse('这里面有小怪兽，不能给你看的~')

def api_homepage(request):
    if request.method == 'POST':
        home_info = request.POST
        home_para = home_info['home_page']
        if home_para == 'homepage':
            home_obj = Booktxt(bookhome = home_para)
            return HttpResponse(json.dumps(home_obj.home_book))
        else:
            return HttpResponse('或许你需要检查你所携带的参数，')
    if request.method != 'POST':
        return HttpResponse('这里面有小怪兽，不能给你看的~')

def api_bookinfo(request):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
    }
    if request.method == 'POST':
        post_info = request.POST
        book_url = post_info['book_url']
        try:
            response = requests.get(book_url,headers = headers)
        except requests.exceptions.MissingSchema:
            return HttpResponse('请检查您的链接，')
        else:
            book_obj = Booktxt(book_url = book_url)
            return HttpResponse(json.dumps(book_obj.book_info))
    if request.method != 'POST':
        return HttpResponse('这里面有小怪兽，不能给你看的~')

def api_chapter(request):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
    }
    if request.method == 'POST':
        post_info = request.POST
        chapter_url = post_info['chapter_url']
        try:
            response = requests.get(chapter_url,headers = headers)
        except requests.exceptions.MissingSchema:
            return HttpResponse('请检查您的链接，')
        else:
            chapter_obj = Booktxt(chapter_url = chapter_url)
            return HttpResponse(json.dumps(chapter_obj.chapter_info))
    if request.method != 'POST':
        return HttpResponse('这里面有小怪兽，不能给你看的~')